package org.example.auth.service;

import org.example.auth.dao.AuthDao;
import org.example.auth.domain.entity.AuthEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 定时任务
 */
@Service
public class ScheduledService {
    @Autowired
    private AuthDao authDao;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 更新权限信息
     * 每30分钟执行一次
     */
    @Scheduled(cron = "0 0/1 * * * ?")
    public void auth(){
        // 从数据库中读取权限信息
        List<AuthEntity> authEntities = authDao.selectList(null);
        // 将数据存储到redis中
        String authPrefix = "auth_";
        for (AuthEntity authEntity : authEntities) {
            redisTemplate.opsForValue().set(authPrefix + authEntity.getToken(), authEntity.getQps(), 1, TimeUnit.HOURS);
        }
    }
}
